package com.uh.microservice.core.spring.mvc;

import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.uh.microservice.core.CONSTANTS;
import com.uh.microservice.core.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.uh.microservice.core.exception.BusinessException;
import com.uh.microservice.core.service.CacheService;
import com.uh.microservice.core.spring.SpringUtil;

/**
 * 参数处理拦截器
 * Created by liming on 2017/9/20.
 */

@Configuration
public class ParamsIntercpetor implements HandlerInterceptor {

    private final LogUtil logger = new LogUtil(this.getClass());
    @Autowired
    private CacheService service;

    /**
     *  pre事件回调接口
     *  从请求中获取json数据，解析后存放在线程变量中
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	String servletPath = request.getServletPath();
    	if(servletPath.toUpperCase().indexOf("FILE") < 0 && !servletPath.equals("/error")) {
	    	String serviceType = SpringUtil.getProp("spring.application.service_type");
	    	if(!"".equals(serviceType) && null != serviceType) {
	    		boolean isPass = false;
	    		String[] serviceTypes = serviceType.split(",");
	    		for(String service : serviceTypes) {
	    			if(service.equalsIgnoreCase("web")) {
	    				isPass = true;
	    				break;
	    			}
	    		}
	    		if(!isPass && servletPath.indexOf("web") != 1) {
	    			throw new BusinessException("THE REQUEST IS NOT ALLOWED!");
	    		}
	    	}
    	}
        //添加每个线程会话ID
        ThreadVariable.getInstance().put(CONSTANTS.CURREN_SID, UUID.randomUUID().toString());
        //获取请求IP地址
        String ip=getIpAddr(request);
        ThreadVariable.getInstance().put(CONSTANTS.REQ_IP,ip);
        Cookie[] cookies=request.getCookies();
        if(cookies != null && cookies.length>0)
            for(Cookie cookie : cookies){
                String key=cookie.getName();
                String value=cookie.getValue();

                if(StringUtils.equals(CONSTANTS.COOKIE_ID, key)){
                    ThreadVariable.getInstance().put(CONSTANTS.REQ_ID,value);
                    if(SpringUtil.isDebug() || true) {
                        Map uinfo = service.findUInfo(value);
                        ThreadVariable.getInstance().put(CONSTANTS.REQ_UKEY, uinfo);
                    }
                }
            }

        return true;
    }

    /**
     *  post事件回调接口
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    /**
     *  after事件回调接口
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}

    /**
     *  从请求中获取IP地址
     */
    private static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }


}
